﻿
using Castle.Core.Internal;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OL_PurInStocksInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {

        public List<OL_FilterDTO> Filters;
        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public OL_PurInStocksInterfaceBusiness()
        {
            this.InterfaceName = "OL采购入库";
            //字段的映射关系
            tableField = GetMapField("getFilterRows");
            //索引字段
            Keys = GetKeys("getFilterRows");
            //indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT  * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置

            //查询执行中的事件
            OnQueryEvent += Interface_Business_OnQueryEvent; ;
            //查询执行前的事件
            BeforeQueryEvent += Interface_Business_BeforeQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += Interface_Business_OnNoQueryEvent;
        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void Interface_Business_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }
        }


        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 新增更新表
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT  * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                //Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                //Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                //Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

                //获取源数据
                List<OL_PurInStocks> sourceData = new List<OL_PurInStocks>();//目标据集合
                var date = DateTime.Now.AddDays(-queryOption.ExcInterval).ToString("yyyy-MM-dd");
                Filters.Clear();
                Filters.Add(
               new OL_FilterDTO() { ControlId = "ctime", DataType = 15, SpliceType = 1, FilterType = 14, Value = date }
           );//创建日期
                sourceData = await QueryAsync<OL_PurInStocks>(queryOption, tableField, SqlDb);

                foreach (var item1 in sourceData)
                {
                    //SKU
                    List<AssTable> table = item1.SKU.ToObject<List<AssTable>>();
                    if (table.Count > 0) item1.SKU = table[0].name;
                    else item1.SKU = "";
                    //需求单号
                    table = item1.Order.ToObject<List<AssTable>>();
                    if (table.Count > 0) item1.Order = table[0].name;
                    else item1.Order = "";
                    //采购组织
                    table = item1.PurOrg.ToObject<List<AssTable>>();
                    if (table.Count > 0) item1.PurOrg = table[0].name;
                    else item1.PurOrg = "";

                    //供应商
                    table = item1.Supplier.ToObject<List<AssTable>>();
                    if (table.Count > 0) item1.Supplier = table[0].name;
                    else item1.Supplier = "";

                }

                //获取目标数据
                //List<OL_PurInStocks> targetData = new List<OL_PurInStocks>();//源数据集合
                //SqlDb._conStrings[0] = queryOption.SourceLink;
                //targetData = SqlDb.GetListBySql<OL_PurInStocks>(@$"SELECT * FROM {queryOption.SourceData}");



                if (this.State > 0 && sourceData.Count > 0)
                {
                    //同步数据库
                    SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                    sqlDBInterface.SqlDb._conStrings[0] = queryOption.SourceLink;
                    sqlDBInterface.ExecuteInterface<OL_PurInStocks>(sourceData, "SD_OL_PurInStocks", @$"WHERE CONVERT(datetime,CreateDate)>='{date}'");
                    //更新
                    #region
                    //List<v_stk_inventory> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<v_stk_inventory>(Keys, "RowId")).ToList();//获取交集(更新项)
                    //List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    //ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    //List<v_stk_inventory> insertItem = sourceData.Except(targetData, new ComparerFromKey<v_stk_inventory>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    //List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    //ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    //List<v_stk_inventory> deleteItem = targetData.Except(sourceData, new ComparerFromKey<v_stk_inventory>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    //List<v_stk_inventory> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    ////将重复的项也一起加入删除的列表
                    //deleteItem.AddRange(repeatItem);
                    ////筛选出删除列表中重复的项
                    //var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //deleteItem.AddRange(temp);
                    //List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    //ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion

                }
                else
                {
                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }




        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }



}
